<template>
  <div
    :class="ismobile ? 'no-scroll' : ''"
    class="w-fill h-auto bg-[#1a2c38] w-full m-auto max-w-[1200px] min-375 text-white"
  >
    <div
      id="iframeId"
      class="iframe_src bg-[#0e1325] w-full m-auto mt-2 md:mt-8"
    ></div>
  </div>
  <div class="real-time-data-dialog pointer-events-auto" v-drag>
    <div class="drag-header" @click="goBack" style="color: transparent">0</div>
  </div>
</template>
<script setup>
import {
  nextTick,
  ref,
  onMounted,
  onDeactivated,
  defineAsyncComponent,
  watch,
  onUnmounted
} from "vue";
import { useRouter, useRoute } from "vue-router";
import { mainAct } from "../../store/activeda";
import Rank from "./components/rank.vue";
import { gameCollect, gameCollectList, gameSame } from "../../api/casion";
import screenfull from "screenfull";
import { useBoolean } from "@/hooks/useBoolean";
const gameBox = defineAsyncComponent(() =>
  import("../../components/gameSwiper/gameBox.vue")
);
import realTimeDataDialog from "./components/realTimeDataDialog.vue";
import { isMobile } from "@/utils/isMobile";

import { eventBus } from "@/utils/eventBus";
import { onBeforeRouteLeave } from "vue-router";
// beforeRouteEnter(() => {
//   console.log("7777777777777", route.query.userToken);
//   // eventBus.emit("iframe-route");
//   // A  B
//   // A edge -> B 谷歌(token)
//   // url + token后八位（A）-> B 谷歌(token)
//   // B的逻辑先取本地后8位 对比 不一样就肯定有问题
// });
const sameGams = ref([]);
const iframe = ref(null);
const main = mainAct();
const router = useRouter();
const route = useRoute();
const game_url = ref("");
const visible = ref(true);

const goBack = () => {
  console.log("/////////////////////", router);
  router.push("/");
};

// 动态创建 iframe
const createIframe = gameUrl => {
  // 确保在创建新的 iframe 之前，先清理旧的 iframe
  clearIframe()
    .then(() => {
      const container = document.getElementById("iframeId");
      // 动态创建 iframe
      const iframe = document.createElement("iframe");
      iframe.src = gameUrl; // 设置 URL
      iframe.frameBorder = 0; // 去掉边框
      iframe.className = "w-full h-full"; // 设置类名
      iframe.allow = "fullscreen"; // 添加允许权限，根据需要扩展
      iframe.onload = () => console.log("Iframe loaded successfully");
      iframe.onerror = () => console.error("Failed to load iframe.");
      container.appendChild(iframe); // 添加到容器
    })
    .catch(err => {
      console.error("Error clearing iframe:", err);
    });
};

// 销毁 iframe
function clearIframe() {
  return new Promise((resolve, reject) => {
    const container = document.getElementById("iframeId");
    if (!container) {
      console.warn("Container for iframe not found.");
      resolve();
      return;
    }

    const iframe = container.querySelector("iframe");
    if (iframe) {
      try {
        // 设置 iframe 为空白页面，释放资源
        iframe.src = "about:blank"; // 或者 iframe.src = "javascript:void(0)";
      } catch (e) {
        iframe.src = "javascript:void(0)";
        console.error("Error setting iframe to blank:", e);
      }

      // 由于跨域问题，直接访问 iframe 内部内容会失败，因此不再清理内部文档
      // 但我们通过清空 src 和移除 iframe 元素，确保资源被释放

      try {
        // 清空 iframe 所占的 DOM 容器
        container.innerHTML = "";
        console.log("Iframe and its resources cleared.");
        resolve();
      } catch (e) {
        console.error("Error clearing iframe container:", e);
        reject(e);
      }
    } else {
      // 如果没有找到 iframe，则直接 resolve
      resolve();
    }
  });
}

watch(
  () => route.query.game_url,
  (newVal, oldVal) => {
    console.log("newVal---main", main.isApp);

    console.log("newVal", newVal == oldVal, newVal, oldVal);

    if (newVal) {
      nextTick(() => {
        game_url.value = newVal;
        createIframe(game_url.value);
      });
    }
  },
  { immediate: true, deep: true }
);

const { boolean, toggle } = useBoolean();
// const { game_url } = route.query; // 获取路由参数
// 是否全屏
const isFullscreen = ref(false);
// 监听变化
const change = () => {
  isFullscreen.value = screenfull.isFullscreen;
};
const ismobile = ref(false);

const handleResize = () => {
  console.log("handleResize", isMobile());
  ismobile.value = isMobile();
};

// 切换事件
const onToggle = () => {
  console.log("iframe.value", iframe.value);

  screenfull.enabled && screenfull.toggle(iframe.value);
  // screenfull.toggle(iframe.value);
};

console.log("游戏传参-" + JSON.stringify(game_url));
const clickStar = async () => {
  // console.log(main.currentGame.code);
  let data = {
    game_code: main.currentGame.code
  };
  let res = await gameCollect(data);
  console.log(res);
  if (res.errno == 0) {
    // 请求收藏夹列表
    // getList();
    if (main.currentGame.is_collect == 1) {
      main.currentGame.is_collect = 0;
    } else {
      main.currentGame.is_collect = 1;
    }
  }
};
const getSameList = async () => {
  let data = {
    game_code: main.currentGame.code,
    page: 1,
    page_size: 7
  };
  let res = await gameSame(data);
  if (res.errno == 0) {
    console.log(res.data.list);
    res.data.list.forEach(item => {
      if (!item.img_url.startsWith("http")) {
        item.img_url = main.static_base_url + item.img_url;
      }
    });
    sameGams.value = res.data.list;
  }
};
// 使用原生事件来替代 screenfull 事件监听
const fullscreenChangeHandler = () => {
  console.log("Fullscreen state changed");
  // 添加处理逻辑
  isFullscreen.value = screenfull.isFullscreen;
  console.log("isFullscreen", isFullscreen.value);
};

onMounted(() => {
  // main.isLoading =false;
  // handleResize();
  handleResize();
  window.addEventListener("resize", handleResize);
  // 监听全屏变化
  document.addEventListener("fullscreenchange", fullscreenChangeHandler);
  document.addEventListener("webkitfullscreenchange", fullscreenChangeHandler);
  //去除百分号和数字
  main.currentGame.name = main.currentGame?.name?.replace(/(\d+%)/, "");
  getSameList();
});

// 删除侦听器
onDeactivated(() => {
  if (screenfull.enabled && typeof screenfull.off === "function") {
    screenfull.off("change", change);
  }
  window.removeEventListener("resize", handleResize);
  document.removeEventListener("fullscreenchange", fullscreenChangeHandler);
  document.removeEventListener(
    "webkitfullscreenchange",
    fullscreenChangeHandler
  );
  console.log("删除侦听器***************************删除侦听器");
});

onUnmounted(() => {
  if (screenfull.enabled && typeof screenfull.off === "function") {
    screenfull.off("change", change);
  }
  window.removeEventListener("resize", handleResize);
  document.removeEventListener("fullscreenchange", fullscreenChangeHandler);
  document.removeEventListener(
    "webkitfullscreenchange",
    fullscreenChangeHandler
  );
  console.log("删除侦听器***************************删除侦听器");
});

const socket = ref(null);

onBeforeRouteLeave(() => {
  clearIframe().then(() => {
    eventBus.emit("game_leave");
  });
  // 主动触发
});
</script>

<style scoped lang="less">
.iframe_src {
  height: 41rem;
}

@media (max-width: 1023px) {
  .iframe_src {
    width: 100%;
    // height: calc(100svh - 148px) !important;
    height: 100%;
    -webkit-overflow-scrolling: touch;
    // overflow: scroll;
  }
}

.no-scroll {
  position: fixed;
  height: 100%;
  overflow: hidden !important;
}

:deep(.scrollable > .routerView) {
  padding: 0 !important;
}
.real-time-data-dialog {
  position: absolute;
  right: 0;
  width: 68px;
  height: 68px;
  display: flex;
  flex-direction: column;
  border-radius: 34px;
  overflow: hidden;
  background: #213743;
  background: url("@/assets/imgs/home.png");
  background-position: no-repeat;
  background-repeat: no-repeat; /* 不重复图片 */
  background-position: center; /* 居中显示 */
}
.drag-header {
  text-align: center;
  line-height: 68px;
}
</style>
